//
//  UIView+MVVM.swift
//  MVVM_BaseViewController
//
//  Created by alyadan on 2016/10/13.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import Foundation
import RxSwift
import YD_Util

var uiview_mvvm_viewModel = 0
var uiview_mvvm_disposeBag = 0

extension UIView : MVVM_ViewProtocol {
    
    //    open override static func initialize() {
    //
    //        swizzlingMethod(token: "UIView" + NSStringFromSelector(#selector(UIView.init(frame:))) , instance: UIView.self, originalSelector: #selector(UIView.init(frame:)), swizzledSelector: #selector(UIView.mvvm_init(frame:)))
    //    }
    //
    @objc open var currentModel: MVVM_BaseViewModel? {
        return viewModel.value
    }
    
    // MARK: Variables
    public var viewModel : Variable<MVVM_BaseViewModel?>{
        get {
            return getViewModel()
        }
    }
    
    public var disposeBag : DisposeBag{
        return getDisposeBag()
    }
    
    
    //MARK: init methods
    public convenience init(viewModel:MVVM_BaseViewModel){
        self.init()
        self.viewModel.value = viewModel
        initView()
    }
    
    
    open override func awakeFromNib() {
        
        super.awakeFromNib()
        initView()
        
    }
    
    public func initView() {
        setupUI()
        addActionTarget()
        bindModelData()
    }
    
    
    
    //MAKR: add variables
    func getDisposeBag() -> DisposeBag{
        var value = objc_getAssociatedObject(self, &uiview_mvvm_disposeBag)
            as? DisposeBag
        
        if value == nil{
            value = DisposeBag()
            objc_setAssociatedObject(self, &uiview_mvvm_disposeBag, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        
        return value!
        
    }
    
    
    func getViewModel() -> Variable<MVVM_BaseViewModel?> {
        
        var value = objc_getAssociatedObject(self, &uiview_mvvm_viewModel)
            as? Variable<MVVM_BaseViewModel?>
        
        if value == nil{
            value = Variable<MVVM_BaseViewModel?>(nil)
            setViewModel(viewModel: value!)
        }
        
        return value!
    }
    
    func setViewModel(viewModel:Variable<MVVM_BaseViewModel?>) {
        objc_setAssociatedObject(self, &uiview_mvvm_viewModel,
                                 viewModel, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    
    //MARK: 工厂方法
    
    @objc open func bindModelData() {}
    
    @objc open func addActionTarget() {}
    
    @objc open func setupUI() {}
}

